from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import UserService
from common.result.Result import Result
from common.enum import BaseEnum
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time
from util.crypto import Crypto

async def Login(req: Request, body: dict):
    try:
        async with in_transaction() as connection:
            # 参数校验
            username, password = body.get('username'), body.get('password')
            if Str.isBlank(username, password):
                Log.error('参数为空，检查参数')
                return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)
            
            # 查询用户
            user = await UserService.loginByUsername(username, Crypto.md5(password))
            if user == None:
                Log.error('用户不存在或密码错误')
                return Result.error(BaseEnum.USER_NOT_EXISTS_OR_PASSWORD_ERROR)
            
            # 构造 Token
            expireTime = Time.format(Time.getUTC8DateTime() + Time.deltaTime(60 * 60 * 24))
            token = Token().generateToken({
                "username": user.username,
                "expire": expireTime
            })

            # 保存 user
            user.update_from_dict({
                "token": token
            })
            await UserService.saveUser(user)

            res = {
                'username': user.username,
                'token': user.token,
                'avatar': user.avatar,
                'email': user.email,
                'create_time': user.create_time,
            }
            return Result.success(res)
    except Exception as e:
        Log.error('登录异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)


